package cn.maiyar.web;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;

import java.util.Objects;

/**
 * 项目启动通知
 *
 * @author c.c
 */
@Slf4j
@Component
public class StartEventListener {

    @Async
    @Order(Ordered.HIGHEST_PRECEDENCE + 10)
    @EventListener(WebServerInitializedEvent.class)
    public void afterStart(WebServerInitializedEvent event) {
        Environment environment = event.getApplicationContext().getEnvironment();
        String serviceName = environment.getProperty("spring.application.name");
        int localPort = event.getWebServer().getPort();
        String profile = org.springframework.util.StringUtils.arrayToCommaDelimitedString(environment.getActiveProfiles());
        log.info("\033[1;32m[{}]启动完成，当前端口:[{}]，环境变量:[{}]\033[0m", serviceName, localPort, profile);
        // nacos
        String namespace = environment.getProperty("spring.cloud.nacos.config.namespace");
        if (StrUtil.isNotEmpty(namespace)) {
            log.info("\033[1;32m当前配置的nacos:[{}]\033[0m", namespace);
        }
        // swagger 接口
        String knife4j = environment.getProperty("knife4j.enable");
        if(StrUtil.isNotEmpty(knife4j) && Objects.requireNonNull(knife4j).equalsIgnoreCase("true")){
            log.info("http://localhost:{}/doc.html", localPort);
        } else {
            log.info("http://localhost:{}", localPort);
        }
//        if (ClassUtils.isPresent("springfox.documentation.spring.web.plugins.Docket", null)) {
//            log.info("http://localhost:{}/doc.html", localPort);
//        } else {
//            log.info("http://localhost:{}", localPort);
//        }
    }
}